var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var imWidget = "";
class Helper {
  constructor() {
  }
  GetBaseUrl(url) {
    if (url.indexOf("?") > 0) {
      return url.split("?")[0];
    } else {
      return url;
    }
  }
  GetUrlQuery(url) {
    let splitUrl = url.split("?");
    if (splitUrl.length <= 1) {
      return false;
    } else {
      let search = "?" + splitUrl[1];
      let theRequest = {};
      if (search.indexOf("?") !== -1) {
        let str = search.substr(1);
        let strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
      }
      return Object.keys(theRequest).length ? theRequest : "";
    }
  }
  ObjectToUrlQuery(queryObj) {
    let arr = Object.keys(queryObj);
    let query = "";
    for (let i in queryObj) {
      query += `${i === arr[0] ? "" : "&"}${i}=${encodeURIComponent(queryObj[i])}`;
    }
    return "?" + query;
  }
  InsertStylesheet(filePath) {
    let link = document.createElement("link");
    link.setAttribute("href", filePath);
    link.setAttribute("rel", "stylesheet");
    let head = document.head || document.getElementsByTagName("head")[0];
    head.append(link);
  }
  removeElement(id) {
    return new Promise((resolve) => {
      const el = document.getElementById(id);
      if (el) {
        let $parent = el.parentElement;
        let rem = $parent.removeChild(el);
        resolve(el === rem);
      } else {
        resolve(true);
      }
    });
  }
  DocumentTitleFlashing() {
    let title = document.title;
    let timer = null;
    let count = 0;
    function change() {
      document.title = (count % 2 === 0 ? "" : "\u3010\u65B0\u6D88\u606F\u3011") + "\u60A8\u6709\u4E00\u6761\u5BA2\u670D\u6D88\u606F";
      count++;
      if (count <= 5) {
        timer = setTimeout(change, 500);
      } else {
        clearTimeout(timer);
        timer = null;
        document.title = title;
        count = 0;
      }
    }
    change();
  }
  BrowserNotification(msg) {
    if (window.Notification) {
      Notification.requestPermission(function(status) {
        console.log("\u6D88\u606F\u901A\u77E5\u6743\u9650\uFF1A", status);
        if (Notification.permission === "granted") {
          const n = new Notification("\u65B0\u6D88\u606F\u901A\u77E5", { tag: "supportMessage", body: msg });
          setTimeout(n.close(n), 3e3);
        }
      });
    }
  }
  PostUrlToIframe(iframeElement) {
    const url = window.location.href + window.location.search + (window.location.search.indexOf("?") < 0 ? "?" : window.location.search.substr(-1, 1) !== "&" ? "&" : "");
    iframeElement.contentWindow.postMessage({ type: "parentMessage", url }, "*");
  }
}
const _ImWidget = class extends Helper {
  constructor(options) {
    super();
    __publicField(this, "customIframeId", "im-service-chat-iframe-custom");
    __publicField(this, "version", "1.1.0");
    __publicField(this, "description", '\u65B0\u589E"custom"\u5C5E\u6027\uFF0C\u63D0\u4F9B\u4EFB\u610F\u5730\u65B9\u653E\u7F6E\u7684\u529F\u80FD');
    __publicField(this, "helper", {
      documentTitleFlashing: this.DocumentTitleFlashing,
      browserNotification: this.BrowserNotification,
      postUrlToIframe: this.PostUrlToIframe
    });
    window.ImWidget = _ImWidget;
    _ImWidget.options = this.SetOption(options);
    _ImWidget.CHATOPEN = _ImWidget.options.open || false;
  }
  SetOption(opt) {
    if (!opt || Object.prototype.toString.call(opt).toLocaleLowerCase() !== "[object object]") {
      opt = {
        url: ""
      };
    }
    if (opt.url) {
      opt.url = decodeURIComponent(opt.url);
    }
    return Object.assign(_ImWidget.options, opt);
  }
  async init() {
    try {
      let rm = await this.removeElement("im-service-chat");
      let body = document.body || document.getElementsByTagName("body")[0];
      if (_ImWidget.options.style) {
        this.InsertStylesheet(_ImWidget.options.style);
      } else {
        console.warn('new ImWidget(options)\u7684options\u672A\u8BBE\u7F6E\u548C"im-widget.umd.js"\u540C\u7EA7\u7684"style.css"\u8DEF\u5F84\uFF0Coptions.style\u5B57\u6BB5\u5C06\u4F5C\u4E3A<link/>\u7684href\u503C\u63D2\u5165<head></head>\uFF0C\u5B8C\u6210\u6302\u4EF6\u7684\u6837\u5F0F\u6E32\u67D3');
      }
      let el = !_ImWidget.options.custom ? await this.initWhereDefault() : await this.initWhereCustom();
      console.log(el);
      if (el) {
        body.append(el);
        console.log("\u521D\u59CB\u5316\u5B8C\u6210");
        ;
        window.ImWidget = this;
      } else {
        console.error("\u521D\u59CB\u5316\u5931\u8D25");
      }
    } catch (err) {
      console.error(err);
    }
  }
  initWhereDefault() {
    return new Promise((resolve2) => {
      let url_params_obj = this.GetUrlQuery(_ImWidget.options.url);
      let el = document.createElement("div");
      let has_title_img = String(url_params_obj.theme || _ImWidget.options.theme).indexOf("http") === 0 || String(url_params_obj.theme || _ImWidget.options.theme).indexOf("//") === 0;
      el.innerHTML = `
            <div id="im-service-chat" class="im-service-chat im-service-chat-${_ImWidget.options.theme} ${_ImWidget.options.open ? "im-service-chat-is-open" : ""} ${has_title_img ? "im-service-chat-has-img" : ""}">
                <button onclick="ImWidget.toggle()" class="im-service-chat-title im-service-chat-title-icon"><span class="im-service-chat-title-top"></span> ${_ImWidget.options.title} <span id="im-service-chat-title-notice" class="im-service-chat-title-notice"></span></button>
                <iframe id="im-service-chat-iframe" class="im-service-chat-iframe" onload="ImWidget.message()" src="${this.RenderUrl(_ImWidget.options)}"></iframe>
            </div>`;
      resolve2(el);
    });
  }
  initWhereCustom() {
    return new Promise((resolve2) => {
      let iframe = document.createElement("iframe");
      iframe.setAttribute("src", _ImWidget.options.url);
      iframe.setAttribute("id", this.customIframeId);
      iframe.setAttribute("class", "im-service-chat-iframe-custom");
      iframe.setAttribute("style", `width:100%;height:100%;border:0;display:${_ImWidget.CHATOPEN ? "block" : "none"};`);
      resolve2(iframe);
    });
  }
  message(callback) {
    window.addEventListener("message", (evt) => {
      console.log(evt.data);
      if (evt.data.type === "message") {
        this.BrowserNotification(evt.data.data);
        this.DocumentTitleFlashing();
        if (!_ImWidget.CHATOPEN) {
          _ImWidget.newMessageCount++;
          this.ChangeUnReadNotice(_ImWidget.newMessageCount);
        } else {
          _ImWidget.newMessageCount = 0;
        }
      }
      if (typeof callback === "function") {
        callback(evt);
      }
    }, false);
  }
  ChangeUnReadNotice(number) {
    let badge = document.getElementById("im-service-chat-title-notice");
    if (number > 0) {
      badge.style.display = "block";
      badge.innerText = number;
    } else {
      badge.innerText = "";
      badge.style.display = "none";
      _ImWidget.newMessageCount = 0;
    }
  }
  RenderUrl(opt) {
    var urlParams = this.GetUrlQuery(_ImWidget.options.url);
    console.log("====>urlParams++++", urlParams);
    if (_ImWidget.options.userInfo) {
      if (_ImWidget.options.userInfo.name) {
        urlParams.from_name = _ImWidget.options.userInfo.name;
      }
      if (_ImWidget.options.userInfo.avatar) {
        urlParams.from_avatar_url = _ImWidget.options.userInfo.avatar;
      }
      if (_ImWidget.options.userInfo.id || _ImWidget.options.userInfo.id_prefix && _ImWidget.options.userInfo.id) {
        urlParams.from_third_party_id = _ImWidget.options.userInfo.id_prefix + _ImWidget.options.userInfo.id;
      }
    }
    urlParams.os_type = "pc";
    return this.GetBaseUrl(_ImWidget.options.url) + this.ObjectToUrlQuery(urlParams);
  }
  toggle(callback) {
    try {
      let handleCallback = function() {
        if (typeof callback === "function" && res) {
          callback(_ImWidget.CHATOPEN);
        }
      };
      let res = false;
      if (_ImWidget.options.custom) {
        this.toggleWhereCustom().then((res2) => {
          if (res2) {
            handleCallback();
          }
        });
      } else {
        this.toggleWhereDefault().then((res2) => {
          if (res2) {
            handleCallback();
          }
        });
      }
    } catch (err) {
      console.error(err);
    }
  }
  toggleWhereDefault() {
    return new Promise((resolve2) => {
      let el = document.getElementById("im-service-chat");
      if (_ImWidget.CHATOPEN) {
        el.className = el.className.replace("im-service-chat-is-open", " ");
      } else {
        el.classList += "im-service-chat-is-open ";
        this.ChangeUnReadNotice(0);
      }
      _ImWidget.CHATOPEN = !_ImWidget.CHATOPEN;
      resolve2(true);
    });
  }
  toggleWhereCustom() {
    return new Promise((resolve2) => {
      if (typeof _ImWidget.options.custom !== "string" || String(_ImWidget.options.custom).indexOf("#") !== 0) {
        resolve2(false);
      } else {
        let containerId = _ImWidget.options.custom.replace("#", "");
        let container = document.getElementById(containerId);
        if (container && container.getElementsByTagName("iframe").length < 1 && this.customIframeId) {
          let iframe = document.getElementById(this.customIframeId);
          if (iframe) {
            let cloneIframe = iframe.cloneNode(true);
            cloneIframe.style.display = "block";
            let containerDOM = document.getElementById(containerId);
            if (containerDOM) {
              containerDOM.append(cloneIframe);
              document.body.removeChild(iframe);
              _ImWidget.CHATOPEN = !_ImWidget.CHATOPEN;
            }
          }
        }
        resolve2(true);
      }
    });
  }
};
let ImWidget = _ImWidget;
__publicField(ImWidget, "CHATOPEN", false);
__publicField(ImWidget, "newMessageCount", 0);
__publicField(ImWidget, "options", {
  theme: "",
  style: "",
  open: false,
  title: "\u8054\u7CFB\u5BA2\u670D",
  url: "",
  custom: false
});
export { ImWidget as default };
